<template>
  <div class="info">
    <!-- 头部导航 -->
    <navBar>
      <template #left>
        <div @click="$router.push('/my')">
          <i class="van-icon van-icon-arrow-left"></i>
        </div>
      </template>
      <template #center>
        <span>个人信息</span>
      </template>
      <template #right>
        <span class="txt" @click="setuser">保存</span>
      </template>
    </navBar>
    <!-- cell卡片 -->
    <van-cell-group>
      <van-cell title="头像" is-link @click="showPopupPic">
        <template #default>
          <!-- 弹出层修改头像 -->
          <img class="pic" :src="userInfo.photo" alt="" />
        </template>
      </van-cell>
      <van-cell title="昵称" is-link @click="showPopupName">
        <template #default>
          <span>{{ userInfo.name }}</span>
        </template>
      </van-cell>
      <van-cell title="介绍" is-link @click="showPopupIntro">
        <template #default>
          <span> {{ userInfo.intro }}</span>
        </template>
      </van-cell>
      <van-cell title="性别" @click="showPopupGender">
        <template #default>
          <span>{{ gender[userGeren.gender] }}</span>
        </template>
      </van-cell>
      <van-cell title="生日" @click="showPopupTiem">
        <template #default>
          <span> {{ userGeren.birthday }}</span>
        </template>
      </van-cell>
    </van-cell-group>
    <!-- 弹出层修改出时间 -->
    <van-popup v-model="showTiem" position="bottom" v-if="show">
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="noShowTiem"
        @confirm="setUserTiem"
      ></van-datetime-picker>
    </van-popup>
    <!-- 弹出层修改性别 -->
    <van-popup v-model="showGender" position="bottom" v-if="showG">
      <van-picker
        show-toolbar
        title="性别"
        :columns="gender"
        :default-index="userGeren.gender"
        @cancel="noShowGender"
        @confirm="setUserGender"
      />
    </van-popup>
    <!-- 弹出层修改介绍 -->
    <van-popup v-model="showIntro" position="bottom">
      <van-field
        v-model="userIntro"
        rows="3"
        autosize
        type="textarea"
        placeholder="请输入介绍"
      />
      <div class="textarea">
        <span
          class="txt1"
          @click="setuserIntro"
          :class="{ colorred: userIntro != userInfo.intro && userInfo.intro }"
          >确定</span
        >
      </div>
    </van-popup>
    <!-- 弹出层修改名称 -->
    <van-popup v-model="showName" position="bottom">
      <van-cell-group>
        <van-field required v-model="userName" @keyup.enter="setuserName" />
      </van-cell-group>
    </van-popup>
    <!-- 弹出层修改头像 -->
    <!-- 上传图片 -->
    <img
      @click="previewImg(imgList)"
      v-for="(item, index) in imgList"
      :key="index"
      :src="imgList"
    />
    <van-popup v-model="showPic" position="center">
      <van-cell-group>
        <div class="items">
          <div class="uploader">
            <div>
              <van-uploader
                :after-read="onRead"
                :before-read="beforeRead"
                :max-size="500 * 1024"
                @oversize="onOversize"
                :max-count="1"
              >
                <div class="one">从相册里面选择</div>
              </van-uploader>
            </div>
          </div>
          <div class="two">拍照</div>
          <div class="three">取消</div>
        </div>
      </van-cell-group>
    </van-popup>
    <!-- 上传图片弹出层显示 -->
  </div>
</template>

<script>
// 图片预览
import { ImagePreview } from 'vant'
import dayjs from 'dayjs'
// 导入dayjs
import relativeTime from 'dayjs/plugin/relativeTime'
import { mapState } from 'vuex'
import { getUserInfoApi, setUserProfile, setPhto } from '../../api/my'
dayjs.extend(relativeTime)
// 导入中文包
dayjs.locale('zh-cn')
export default {
  name: 'info',
  data () {
    return {
      // 性别设置'
      userGender: { 0: '男', 1: '女' },
      // 个人信息对象
      userGeren: '',
      // 是否显示生日
      showTiem: false,
      showGender: false,
      showIntro: false, // 个人介绍
      showName: false,
      showPic: false,
      // 个人昵称
      userName: '',
      // 个人介绍
      userIntro: '',
      // 时间参数
      tiem: '', // 发送请求是修改的时间
      year: 2021,
      month: 0,
      day: 17,
      minDate: new Date(1900, 0, 1),
      maxDate: new Date(2025, 11, 1),
      currentDate: new Date(2021, 0, 17),
      show: true,
      showG: true,
      // 性别设置
      gender: ['男', '女'],
      // 上传图片地址
      fileList: [],
      // 图片列表
      imgList: [],
      previewImgDialog: '',
      // 弹出层图片是否确定上传
      file: '',
      // 图片动态显示
      picshow: ''
    }
  },
  computed: {
    ...mapState(['userInfo'])
  },
  methods: {
    // 获取用户个人信息
    gettime () {
      this.year = Number(this.userGeren.birthday.split('-')[0])
      this.month = Number(this.userGeren.birthday.split('-')[1]) - 1
      this.day = Number(this.userGeren.birthday.split('-')[2])
      // 默认渲染时间
      this.currentDate = new Date(this.year, this.month, this.day)
    },
    async getUserInfo () {
      const res = await getUserInfoApi()
      console.log(res)
      this.userGeren = res.data
      this.userName = this.userInfo.name
      this.gettime()
      // 时间字符串
    },
    // 显示生日
    showPopupTiem () {
      // 静默刷新
      this.gettime()
      this.show = false
      setTimeout(() => {
        this.showTiem = true
        this.show = true
      }, 0)
    },
    // 取消关闭生日
    noShowTiem () {
      this.showTiem = false
    },

    // 取消关闭性别
    noShowGender () {
      this.showGender = false
    },
    // 显示介绍
    showPopupIntro () {
      this.userIntro = this.userInfo.intro
      this.showIntro = true
    },
    // 显示性别
    showPopupGender () {
      this.showGender = true
      this.showG = false
      setTimeout(() => {
        this.showG = true
      }, 0)
    },
    // 显示昵称
    showPopupName () {
      this.userName = this.userInfo.name
      this.showName = true
    },
    // 显示头像
    showPopupPic () {
      this.showPic = true
    },
    // 点击修改姓名
    async setuserName () {
      const res = await setUserProfile({
        name: this.userName
      })
      console.log(res)
      // 动态渲染
      this.$store.commit('setUserInfo', { name: res.data.name })
      this.showName = false
    },
    // 点击修改介绍
    async setuserIntro () {
      const res = await setUserProfile({
        intro: this.userIntro
      })

      // 动态渲染
      this.$store.commit('setUserInfo', { intro: res.data.intro })
      this.showIntro = false
    },
    // 点击修改生日
    async setUserTiem (value) {
      console.log(value)
      this.tiem = dayjs(value).format('YYYY-MM-DD')
      const res = await setUserProfile({
        birthday: this.tiem
      })
      // 默认渲染时间
      this.currentDate = value
      this.userGeren.birthday = res.data.birthday
      // 动态渲染
      this.showTiem = false
    },
    // 点击修改性别
    async setUserGender (text) {
      // 非必须 性别，0-男，1-女
      this.userGeren.gender = text === '男' ? 0 : 1
      const res = await setUserProfile({
        gender: this.userGeren.gender
      })
      // this.getUserInfo()
      console.log(res)
      this.userGeren.gender = res.data.gender
      // 动态渲染
      this.showGender = false
      // 发送请求修改性别
    },
    // 文件上传前回调函数
    beforeRead (file) {
      if (file.type !== 'image/jpeg') {
        this.$toast('请上传 jpg 格式图片')
        return false
      }
      return true
    },
    // 捕获文件上传限制大小
    onOversize (file) {
      this.$toast('文件大小不能超过5M')
    },
    // 上传图片点击事件
    async onRead (file) {
      console.log(file)
      this.file = file.file
      // 图片上预览
      this.imgList.push(file.content)
      // 关闭弹窗
      this.showPic = false
      // 遮罩层显示图片
      this.previewImg()
      // 完成之清空图片
      this.imgList = []
    },
    // 调用全局显示
    previewImg (imgs, index) {
      // 图片的弹出层关闭
      var isFlag = true
      var that = this
      if (isFlag) {
        this.previewImgDialog = ImagePreview({
          images: this.imgList,
          startPosition: index,
          onClose () {
            isFlag = false
            if (!isFlag) {
              this.$dialog
                .confirm({
                  message: '是否设置该图片为头像'
                })
                .then(async () => {
                  const res = await setPhto(that.file)
                  console.log(11111)
                  console.log(res)
                  that.$store.commit('setUserInfo', { photo: res.data.photo })
                })
                .catch(() => {})
            }
          }
        })
        // this.toemID = setInterval(() => {
        //   console.log(2222)
        //   if (!isFlag) {
        //     this.$dialog
        //       .confirm({
        //         message: '是否设置该图片为头像'
        //       })
        //       .then(async () => {
        //         const res = await setPhto(this.file)
        //         console.log(res)
        //         this.userInfo.photo = res.data.photo
        //       })
        //       .catch(() => {})
        //     clearInterval(this.toemID)
        //   }
        // }, 1000)
      }
    },
    // 保存修改后的数据
    setuser () {
      this.$dialog
        .confirm({
          message: '确定修改用户信息？'
        })
        .then(async () => {
          this.setuserName()
          this.setuserIntro()
          this.setUserTiem()
          this.setUserGender()
          this.$toast.success('保存成功')
        })
        .catch(() => {})
    }
  },
  created () {
    this.$store.dispatch('setUserInfo')
    this.getUserInfo()
    // 获取介绍
    this.userIntro = this.userInfo.intro
  }
  // showTiem (newval) {
  //   if (!newval) {
  //     this.show = true
  //   }
  // }
}
</script>

<style lang="less">
.info {
  padding-top: 50px;
  .txt {
    font-size: 12px;
  }
  .pic {
    width: 26px;
    height: 26px;
    border-radius: 50%;
  }
  .textarea {
    text-align: right;
    box-sizing: border-box;
    .txt1 {
      padding: 5px 10px;
      display: inline-block;
      border-radius: 10px;
      background-color: #eee;
      margin-right: 10px;
      font-size: 16px;
    }
    // 绑定一个类名显示red
    .colorred {
      color: #3e9df8;
    }
  }
  .items {
    width: 266px;
    text-align: center;
    .two {
      padding: 10px 0;
      border-top: 1px solid #ccc;
      border-bottom: 1px solid #ccc;
    }
    .one {
      padding: 10px 0;
    }
    .three {
      padding: 10px 0;
    }
  }
}
</style>
